const express = require('express');
const http = require('http');
const path = require('path');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const morgan = require('morgan');
const fs = require('fs').promises;
const config = require('./config');
const logger = require('./utils/logger');
const chatService = require('./services/chatService');
const asrService = require('./services/asrService');
const ttsService = require('./services/ttsService');
const weatherService = require('./services/weatherService');
const familyService = require('./services/familyService');

/**
 * 创建并配置Express应用程序
 */
async function createApp() {
  // 创建Express应用
  const app = express();
  
  // 创建HTTP服务器
  const server = http.createServer(app);
  
  // 创建单独的WebSocket服务器
  const wsServer = http.createServer();
  
  // 配置中间件
  app.use(helmet(config.security.helmet));
  app.use(compression(config.compression));
  app.use(cors(config.cors));
  app.use(express.json({ limit: '10mb' }));
  app.use(express.urlencoded({ extended: true, limit: '10mb' }));
  app.use(morgan('combined', { stream: logger.stream }));
  
  // 确保上传目录存在
  await fs.mkdir(config.upload.destination, { recursive: true });
  
  // 静态文件服务
  app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
  app.use(express.static(config.static.path, config.static.options));
  
  // 初始化服务
  chatService.setWebSocketServer(wsServer);
  asrService.init();
  await ttsService.init();
  await weatherService.init();
  await familyService.init();
  
  // 设置API路由
  app.use(config.apiPrefix, require('./routes'));
  
  // 处理前端路由（SPA）
  app.get('*', (req, res) => {
    res.sendFile(path.join(config.static.path, 'index.html'));
  });
  
  // 错误处理中间件
  app.use((err, req, res, next) => {
    logger.error(`API错误: ${err.message}`);
    logger.error(err.stack);
    
    res.status(err.status || 500).json({
      error: {
        message: err.message || '服务器内部错误',
        status: err.status || 500
      }
    });
  });
  
  return { app, server, wsServer };
}

module.exports = createApp;